package com.cyberx.slackspringbootstarter.service;

import com.cyberx.slackspringbootstarter.exception.SlackConfigInvalidException;
import com.cyberx.slackspringbootstarter.properties.BotConfig;
import com.cyberx.slackspringbootstarter.properties.ChannelConfig;
import com.cyberx.slackspringbootstarter.properties.SlackProperties;
import java.util.Optional;

/**
 * Slack操作功能，主要用于通过 Slack配置的机器人发送消息，参考：<a
 * href="https://slack.dev/java-slack-sdk/guides/web-api-basics">Slack SDK for java</a>
 */
public class Slack {
  private final SlackProperties properties;
  private final com.slack.api.Slack slackInstance;

  public Slack(SlackProperties properties) {
    this.properties = properties;
    this.slackInstance = com.slack.api.Slack.getInstance();
  }

  /**
   * 根据 channel，botName获取机器人实例。
   *
   * @param channelId 频道名称
   * @param botId 机器人名称
   * @return 机器人实例
   * @throws SlackConfigInvalidException 机器人配置信息错误
   */
  public Api of(String channelId, String botId) throws SlackConfigInvalidException {
    // 查询频道配置
    Optional<ChannelConfig> optionalChannelConfig =
        this.properties.getChannelConfigList().stream()
            .filter(config -> config.getId().equals(channelId))
            .findFirst();
    // 查询机器人配置
    Optional<BotConfig> optionalBotConfig =
        this.properties.getBotConfigList().stream()
            .filter(config -> config.getId().equals(botId))
            .findFirst();
    if (optionalChannelConfig.isEmpty() || optionalBotConfig.isEmpty()) {
      throw new SlackConfigInvalidException();
    }
    ChannelConfig channelConfig = optionalChannelConfig.get();
    BotConfig botConfig = optionalBotConfig.get();
    return new Api(slackInstance, channelConfig, botConfig);
  }
}
